<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-10-31
 * Time: 上午8:23
 */

namespace System;

class View
{

    public $file;
    private $expired = 0;
    private $temp_cache = "assets/cache/";
    private $temp_path = "App/Views/";
    private $file_ext = ".php";
    private $keys = array(
        '{if %%}' => '<?php if (\1): ?>',
        '{elseif %%}' => '<?php ; elseif (\1): ?>',
        '{for %%}' => '<?php for (\1): ?>',
        '{foreach %%}' => '<?php foreach (\1): ?>',
        '{while %%}' => '<?php while (\1): ?>',
        '{/if}' => '<?php endif; ?>',
        '{/for}' => '<?php endfor; ?>',
        '{/foreach}' => '<?php endforeach; ?>',
        '{/while}' => '<?php endwhile; ?>',
        '{else}' => '<?php ; else: ?>',
        '{continue}' => '<?php continue; ?>',
        '{break}' => '<?php break; ?>',
        '{$%% = %%}' => '<?php $\1 = \2; ?>',
        '{$%%++}' => '<?php $\1++; ?>',
        '{$%%--}' => '<?php $\1--; ?>',
        '{$%%}' => '<?php echo $\1; ?>',
        '{url(%%)}' => '<?php echo site_url(\1);?>',
        '{comment}' => '<?php /*',
        '{/comment}' => '*/ ?>',
        '{/*}' => '<?php /*',
        '{*/}' => '*/ ?>',
        '{%%\?%%\:%%}' => '<?php echo \1?\2:\3;?>',
        '{var %%}' => '<?php var_dump(\1);?>',
    );

/* 未声明变量数组 */
    public $vars = array();

    public function __construct($path = null)
    {
        if (is_array($path)) {
            $this->expired = isset($path['expired']) ? $path['expired'] : 0;
            $this->temp_path = isset($path['path']) ? $path['path'] : 'views/';
        } else if (is_string($path)) {
            $this->temp_path = $path;
        }
        return $this;
    }

    public function setFile($template)
    {
        $this->file[] = $template;
    }

    public function get($key)
    {
        return $this->__get($key);
    }

// 获取所有未声明变量
    public function getVars()
    {
        return $this->vars ?: null;
    }

// 获取类中未声明变量
    public function __get($key)
    {
        return isset($this->vars[$key]) ? $this->vars[$key] : null;
    }

// 设置类中未声明变量
    public function __set($key, $val)
    {
        $this->vars[$key] = $val;
    }

    public function set($key, $val)
    {
        $this->__set($key, $val);
        return $this;
    }

    public function setKey($key, $val)
    {
        $this->keys[$key] = $val;
        return $this;
    }

// 设定模板路径
    public function setPath($path)
    {
        $this->temp_path = $path;
        return $this;
    }

// 设置缓存时间，以分钟为单位
    public function setExtens($time)
    {
        $this->expired = $time * 60;
        return $this;
    }

//设置缓存路径
    public function setCachePath($path)
    {
        if (is_dir($path)) {
            $this->temp_cache = $path;
        } else {
            $lang = new \System\Language();
            die($lang->cachePathNotExist . $path);
        }
        return $this;
    }

// 转换
    private function compile($file)
    {
        $temp_cache = new \System\Cache(array(
            'cache_name' => md5($file),
            'cache_path' => $this->temp_cache,
            'cache_expired' => $this->expired,
            'cache_extension' => $this->file_ext,
        ));

        $temp_cache->eraseExpired();

        if ($temp_cache->cached("html")) {
            $filestr = $temp_cache->get("html");
        } else {
            foreach ($this->keys as $key => $val) {
                $patterns[] = '#' . str_replace('%%', '(.+)', preg_quote($key, '#')) . '#U';
                $replace[] = $val;
            }
            $filestr = preg_replace($patterns, $replace, file_get_contents($this->temp_path . $file . $this->file_ext));
            $temp_cache->set("html", $filestr);
        }
        return $filestr;
    }

    public function toString()
    {
        $template = '';

        foreach ($this->file as $file) {
            $template .= $this->compile($file);
        }
        $this->file = [];
        extract($this->getVars());
        ob_start();
        eval("?>" . $template);
        $output = ob_get_contents();
        @ob_end_clean();

        return $output;
    }

// 设置要显示的内容文件
    public function display($template)
    {
        if (is_file($this->temp_path . $template . $this->file_ext)) {
            $this->setFile($template);
        } else {
            $lang = new \System\Language();
            showError($lang->templeteFileNotExist . $this->temp_path . $template . $this->file_ext);
        }
        return $this;
    }

// 输出模板文件
    public function render()
    {
        $template = '';

        foreach ($this->file as $file) {
            $template .= $this->compile($file);
        }

        return $this->evaluate($template, $this->getVars());
    }

// 转换成php
    private function evaluate($code, array $variables = null)
    {
        if ($variables != null) {
            extract($variables);
        }

        return eval('?>' . $code);
    }

}
